package com.controller.manager;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.pojo.User;
import com.service.UserService;
import com.utils.Base64Util;
import com.utils.Md5Utils;

@Controller
@RequestMapping("/")
public class LoginController {

	@Resource
	private UserService userService;

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String adminLogin(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "message", required = false) String message) {
		request.getSession().removeAttribute("username");
		request.setAttribute("message", message);
		return "/login";
	}

	@RequestMapping(value = "/admin/login", method = RequestMethod.POST)
	@ResponseBody
	public int pcAdminlogin(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "username", required = false) String username,
			@RequestParam(value = "password", required = false) String password) {

		// 通过用户名获取用户信息
		User user = userService.findByUsername(username);
		if (user == null) {
			return -2;// 用户不存在
		} else {
			String password2 = user.getPassword();
			if (StringUtils.isNotEmpty(password) && StringUtils.isNotEmpty(password2)
					&& StringUtils.equals(Base64Util.encodeData(password), password2)) {
				request.getSession().setAttribute("username", username);
				request.getSession().setAttribute("user", user);
				return 1;
			} else {
				return -1;// 用户名或者密码错误
			}
		}
	}

	@RequestMapping(value = "/admin/manager/index", method = RequestMethod.GET)
	public String adminManagerIndex() {
		return "/manager/index";
	}

	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	@ResponseBody
	public String logout(HttpServletRequest request, HttpServletResponse response) {
		// 注销用户，使session失效。
		request.getSession().invalidate();
		response.setHeader("Cache-control", "no-store");
		response.setHeader("referer", "");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Pragma", "no-cache");
		response.setDateHeader("expires", -1);
		return "success";
	}
}
